properties([
   parameters([
      [
         $class: 'ParameterSeparatorDefinition',
         name: 'DISTRIBUTE_HEADER',
         sectionHeader: 'Distribute Parameters',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],
      string(name: 'START_WORK_INDEX', defaultValue: '0', description: ''),
      string(name: 'END_WORK_INDEX', defaultValue: '1', description: ''),
      choice(name: 'EXECUTE_NODE', choices: utils.allOnlineNodes(), description: '执行节点'),
      choice(name: "PROJECT", choices: config.allProjects(), description: '执行工程'),

      [
         $class: 'ParameterSeparatorDefinition',
         name: 'BUILD_HEADER',
         sectionHeader: 'Build Parameters',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],
      booleanParam(name: 'FORCE_REBUILD_LIBRARY', defaultValue: false, description: '在 dry-run 时，重编 library'),
      booleanParam(name: 'assetbundle_mask', defaultValue: true, description: '是否加密AB包'),

      [
         $class: 'ParameterSeparatorDefinition',
         name: 'IGNORE_HEADER',
         sectionHeader: 'Ignore Parameters',
         separatorStyle: config.separatorStyle(),
         sectionHeaderStyle: config.sectionHeaderStyle()
      ],      
      booleanParam(name: 'SKIP_PREPARE_PROJECT', defaultValue: false, description: '跳过工程准备'),
      booleanParam(name: 'SKIP_PREPARE_LIBRARY', defaultValue: false, description: '跳过 Library 准备'),
      booleanParam(name: 'SKIP_DRY_RUN', defaultValue: true, description: '跳过 dry-run 阶段'),
      booleanParam(name: 'SKIP_BUILD', defaultValue: false, description: '跳过编译阶段'),
    ])
 ])

def rebuildLibraryArgvs()
{
   if(params.FORCE_REBUILD_LIBRARY)
      return " -rebuildlibrary "
   else
      return ""
}

node( "${params.EXECUTE_NODE}" )
{
   stage("Prepare")
   {
      if(params.SKIP_PREPARE_PROJECT == false)
      {
         utils.createLockFile(params.PROJECT, params.EXECUTE_NODE)

         // 准备 unity 程序
         config.copyUnityDir(params.EXECUTE_NODE)
         // 准备工程
         if(params.PROJECT == 'Chijin')
         {
            def svnProjectPath = config.localProjectDir(params.PROJECT, params.EXECUTE_NODE)
            utils.prepareSVNProject(svnProjectPath)
         }

         utils.deleteLockFile(params.PROJECT, params.EXECUTE_NODE)
      }

      if(params.SKIP_PREPARE_LIBRARY == false)
      {
         def originProjectDir = config.sharedProjectDir(params.PROJECT)

         // 拷贝工程到worker
         config.prepareLocalProject(params.PROJECT, params.EXECUTE_NODE)

         // 创建log目录
         def logDir = "${originProjectDir}/${config.distributeLogDir()}"
         if(params.EXECUTE_NODE == config.masterNodeName())
            logDir = "${config.mountProjectDir(params.PROJECT)}/${config.distributeLogDir()}"
         sh "if [ ! -d ${logDir} ]; then ( mkdir ${logDir} ) fi"
      }
   }

   stage("Dry run")
   {
      if(params.SKIP_DRY_RUN == false)
      {
         utils.createLockFile(params.PROJECT, params.EXECUTE_NODE)

         def originProjectDir = config.sharedProjectDir(params.PROJECT)
         // 日志文件
         def logDir = "${originProjectDir}/${config.distributeLogDir()}"
         if(params.EXECUTE_NODE == config.masterNodeName())
            logDir = "${config.mountProjectDir(params.PROJECT)}/${config.distributeLogDir()}"
         def logFile = "${logDir}/worker${config.buildName()}-${params.EXECUTE_NODE}-${params.START_WORK_INDEX}-${params.END_WORK_INDEX}-dryrun.log"

         def localProjectDir = config.localProjectDir(params.PROJECT, params.EXECUTE_NODE)
         try
         {
            sh """
               ${config.localUnityPath(params.EXECUTE_NODE)} -quit -batchmode \
               -projectPath ${localProjectDir}                                \
               -logfile ${logFile}                                            \
               ${rebuildLibraryArgvs()}
            """
         }
         catch(err)
         {
            echo "Failed to dry run."
            currentBuild.result = 'FAILURE'
         }

         utils.deleteLockFile(params.PROJECT, params.EXECUTE_NODE)
      }
   }

   stage('Build Bundles')
   {
      if(params.SKIP_BUILD == false)
      {
         echo "Build Asset Bundles in ${params.EXECUTE_NODE}"

         def originProjectDir = config.sharedProjectDir(params.PROJECT)
         // 日志文件
         def logDir = "${originProjectDir}/${config.distributeLogDir()}"
         if(params.EXECUTE_NODE == config.masterNodeName())
            logDir = "${config.mountProjectDir(params.PROJECT)}/${config.distributeLogDir()}"
         def logFile = "${logDir}/worker${config.buildName()}-${params.EXECUTE_NODE}-${params.START_WORK_INDEX}-${params.END_WORK_INDEX}.log"
         
         // 运行打包程序
         def localProjectDir = config.localProjectDir(params.PROJECT, params.EXECUTE_NODE)
         
         def mainfestFilePath = "${originProjectDir}/distribute.manifest"
         if(params.EXECUTE_NODE == config.masterNodeName())
            mainfestFilePath = "${config.mountProjectDir(params.PROJECT)}/distribute.manifest"

         try
         {
            sh """
               ${config.localUnityPath(params.EXECUTE_NODE)} -quit -batchmode                               \
               -projectPath ${localProjectDir}                                                              \
               -distributedWorker ${mainfestFilePath} ${params.START_WORK_INDEX} ${params.END_WORK_INDEX}   \
               -logfile ${logFile}                                                                          \
               -assetbundle_mask ${params.assetbundle_mask}                                                 \
               -ignoreResourceChecking
            """
         }
         catch(err)
         {
            echo "Failed to build asset bundles."
            currentBuild.result = 'FAILURE'
         }


         utils.deleteLockFile(params.PROJECT, params.EXECUTE_NODE)
      }
   }
}
